package user

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"organoid_public/global"
	"organoid_public/pkg/logger"
)

type handler struct {
	log logger.Logger
	svc *service
}

// 初始化表示层的handler(发现应用层的svc)
func newHandler() (*handler, error) {
	svc, err := newService()
	if err != nil {
		return nil, err
	}
	return &handler{
		svc: svc,
		log: global.Log,
	}, nil
}

/*
*
登录
1.通过jwt生成token
*/
func (h *handler) loginIn(c *gin.Context) {
	var (
		params   LoginReq
		response = global.Response.New(c)
	)
	err := response.BindWithValidate(&params)
	if err != nil {
		response.Error(err).ToJSON()
	}
	data, err := h.svc.loginIn(&params)
	if err != nil {
		response.Error(err).ToJSON()
	} else {
		response.Success(data).ToJSON()
	}

}

// 登出
func (h *handler) loginOut(c *gin.Context) {
	var (
		params   LoginOutReq
		response = global.Response.New(c)
	)
	err := response.BindWithValidate(&params)
	if err != nil {
		response.Error(err).ToJSON()
		return
	}

	tokenId, _ := c.Get("tokenId")
	_, err = h.svc.LoginOut(tokenId.(string))
	if err != nil {
		response.Error(err).ToJSON()
		return
	}
	response.Success("ok").ToJSON()
	fmt.Println(123)
}

// 头像上传(io+path)
func (h *handler) headImgUpload(c *gin.Context) {
	var (
		params   HeadImgUpReq
		response = global.Response.New(c)
	)
	//file, _ := c.FormFile("file")
	//dst := "./" + file.Filename
	//// 上传文件至指定的完整文件路径
	//c.SaveUploadedFile(file, dst)
	//fmt.Println(c)
	err := response.BindWithValidate(&params)
	if err != nil {
		response.Error(err).ToJSON()
		return
	}
	err = h.svc.headImgUpload(&params)
	if err != nil {
		response.Error(err).ToJSON()
	}
	response.Success("").ToJSON()
}

/*
*
登录检验
主要是通过jwt校验token是否有效
*/
func (h *handler) checkAuth(c *gin.Context) {
	var (
		Token    string
		response = global.Response.New(c)
	)

	Token = c.Request.Header.Get("Token")
	if len(Token) <= 0 {
		response.Error(errors.New("非法请求")).ToJSON()
		return
	}
	res, err := h.svc.CheckAuth(Token)
	if err != nil {
		response.Error(err).ToJSON()
		return
	}
	c.Set("userId", res.Uid)
	c.Set("userName", res.Name)
	c.Set("tokenId", res.Id)

}

// 测试content
func (h *handler) testContent(c *gin.Context) {

}

// 测试os
func (h *handler) testOs(c *gin.Context) {

}
